package com.chj.service;

import com.chj.dao.DictionaryEntityMapper;
import com.chj.dao.OrderEntityMapper;
import com.chj.dao.OrderItemEntityMapper;
import com.chj.entity.DictionaryEntity;
import com.chj.entity.OrderEntity;
import com.chj.entity.OrderItemEntity;
import com.chj.entity.ext.OrderEntityExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderService {

    @Autowired
    private OrderEntityMapper orderMapper;

    @Autowired
    private OrderItemEntityMapper orderItemMapper;

    @Autowired
    private DictionaryEntityMapper dictionaryMapper;

    @Transactional
    public long addOne1(OrderEntity entity) {
        this.orderMapper.insert(entity);
        return entity.getId();
    }

    public List<OrderEntity> getList1() {
        return this.orderMapper.selectByMap(new HashMap<>());
    }

    @Transactional
    public long addOne2(OrderEntityExt entity) {
        this.orderMapper.insert(entity);
        for (OrderItemEntity orderItem : entity.getOrderItems()) {
            orderItem.setOrderNum(entity.getOrderNum());
            orderItemMapper.insert(orderItem);
        }
        return entity.getId();
    }

    public OrderEntityExt getOne2(Long orderNum) {
        Map<String,Object> orderQueryMap = new HashMap<>();
        orderQueryMap.put("order_num", orderNum);
        List<OrderEntity> orders = orderMapper.selectByMap(orderQueryMap);
        OrderEntityExt order = new OrderEntityExt();
        if(orders != null && orders.size() == 1){
            BeanUtils.copyProperties(orders.get(0), order);
            Map<String,Object> orderItemQueryMap = new HashMap<>();
            orderItemQueryMap.put("order_num", orderNum);
            List<OrderItemEntity> orderItems = orderItemMapper.selectByMap(orderItemQueryMap);
            order.setOrderItems(orderItems);
        }
        return order;
    }

    /**
     * 同库分表事务测试
     */
    @Transactional
    public long addOne3(OrderEntityExt entity) {
        this.orderMapper.insert(entity);
        for (OrderItemEntity orderItem : entity.getOrderItems()) {
            orderItem.setOrderNum(entity.getOrderNum());
            orderItemMapper.insert(orderItem);
        }
        throw new RuntimeException();
//        return entity.getId();
    }

    /**
     * 不同库分表事务测试
     */
    @Transactional
    public long addOne4(OrderEntity entity, DictionaryEntity dictionary) {
        this.orderMapper.insert(entity);
        this.dictionaryMapper.insert(dictionary);
        throw new RuntimeException();
//        return entity.getId();
    }
}
